<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 订单管理API
 * @author zxj
 *
 */
class Orders extends CI_Controller {
	private $t_order = 'mt_order';  //订单表
	function __construct() {
		parent::__construct();
        //$this->output->enable_profiler(TRUE);
        $this->load->model('api_model/tr_order_model','trOrderModel');
	}



    /**
     * 获取来货追踪号
     */
    function setShipinTrack(){
        $gpData = gp();
        $oid = $gpData['oid'];
        $shipinTrack = $gpData['shipinTrack'];
        $remark = $gpData['remark'];
        if(is_numeric($oid)){
            $where = array('id'=>$oid);
        }else{
            $where = array('order_num'=>$oid);
        }
        $orders = $this->common_model->selectFirst('mt_order',$where);
        if(!$orders){
            json_output($gpData,'Order not exist',false);
        }
        $result = $this->common_model->update('mt_order',array('shipinTrack'=>$shipinTrack,'remark'=>$remark),$where);
        if(!$result){
            json_output($result,'update failed',false);
        }
        json_output($result,'Update successful',true);
    }



    /**
     * 更改保内保外
     */
    function setWarranty(){
        $this->load->model('fee_model');
        $gpData = gp();
        log_output($gpData);
        $pid = $gpData['pid'];
        $seller_warranty = $gpData['seller_warranty'];
        $where = array('id'=>$pid);
        $productOne = $this->common_model->selectFirst('mt_product',$where);
        if(!$productOne){
            json_output($gpData,'product not exist',false);
        }
        $result = $this->common_model->update('mt_product',array('seller_warranty'=>$seller_warranty,'available'=>1),$where);
        if($productOne['status_id']==5){
            //清除报价
            $this->common_model->clearOrder($productOne['oid']);
            $this->common_model->clearProduct($productOne['id']);
            $this->fee_model->setProductPrice($pid);
            $this->common_model->sendStatusWebsite($productOne['oid']);
        }
        json_output($result,'Update successful',true);
    }


    /**
     * 更新订单入库OR发货
     */
    function setStoreOrShip(){
        $gpData = gp();
        $oid = $gpData['oid'];
        $storeOrShip = intval($gpData['storeOrShip']);
        $orders = $this->common_model->selectFirst('mt_order',array('id'=>$oid));
        if(!$orders){
            json_output($gpData,'Order not exist',false);
        }
        if($storeOrShip == $orders['storeOrShip']){
            json_output($orders,'No change.',false);
        }
        $sql = 'select * from mt_product where oid='.$oid.' and isQcPass is not NULL ;';
        $isQc = $this->common_model->getQuery($sql);
        if($isQc){
            json_output($isQc,'Update failed, can not update after QC',false);
        }
        $setData = array('storeOrShip'=>$storeOrShip);
        if($storeOrShip==2){
            $setData['delivery_service'] = 0;
        }else {
            $setData['delivery_service'] = 1;
        }
        $result = $this->common_model->update('mt_order',$setData,array('id'=>$oid));
         //reload begin sqingwen 20170111
        $sql = sprintf("select `id` from `mt_product` where `oid` = '%s'", $oid);
        $product = $this->db->query($sql)->result_array();
        $logInfo = array('file_path' => __FILE__, 'fun' => __FUNCTION__, 'pro:' => 'prd', 'data' => $product);
        log_output($logInfo);
        if ($product) {
            $this->load->model('fee_model', 'feeModel');
            foreach ($product as $k => $v) {
                $id = intval($v['id']);
                $res = $this->feeModel->setProductPrice($id); //这个id是产品表的id
            }
        }
        //reload end
	if(!$result){
            json_output($result,'update failed',false);
        }
        json_output($result,'Update successful',true);

    }



    /**
     * 订单列表
     */
    function index()
    {
        //输出数据结构
        $status = 0;
        $gpData = $formData = gp();  // get post data
        //查询条件
        //添加了一个order_type字段筛选20170210 sqingwen
	//应tr要求，增加, 'startDate' , 'endDate' 用于时间筛选
        $fieldsProduct = array('imei',);
        $fieldsOrder = array('merchant_num' ,'point' ,'status_id' ,'source_oid','shipinTrack','shipoutTrack');
        $fieldsExt = array('order_num' ,'startTime' , 'endTime' , 'order_type', 'startDate' , 'endDate','customer_name');
        //字段合集
        $fieldsList = array_merge($fieldsProduct, $fieldsOrder, $fieldsExt);
        //允许模糊搜索的字段
        $fieldsLike = array('imei','source_oid','shipinTrack','shipoutTrack');
        //接受参数
        $where = ' b.available !=0 and ';
        //拼接查询字符串
        foreach ($formData as $key => $val) {
            $val = trim($val);
            if (!$val || !in_array($key, $fieldsList)) continue;
            if ($key == 'startTime' || $key == 'endTime'||$key == 'startDate' || $key == 'endDate') {
                if ($key == 'startTime' || $key == 'startDate' ) {
                    $where .= 'b.create_time >=\'' . $val . ' 00:00:00\'';
                }
                if ($key == 'endTime'||$key == 'endDate') {
                    $where .= 'b.create_time <=\'' . $val . ' 23:59:59\'';
                }
            }elseif($key == 'merchant_num'){
                if (is_numeric($val)) {
                    $where .= 'b.merchant_num = '.$val;
                } else {
                    $merchantIds = json_decode($val,true);
                    $where .= 'b.merchant_num in('.implode(',',$merchantIds).')';
                }
            }elseif($key == 'status_id'){
                if($val == '-1'){
                    $where .= '(a.available = 2 or b.available = 2)';
                }elseif($val == '-2'){
                    $where .= 'b.arrivalRate >= 1';
                } else{
                    $where .= 'b.status_id = '.$val;
                }
            }
            //tomrepair需求，添加订单类型参数筛选订单
            //sqingwen 20170210
            elseif ($key == 'order_type') {
                $where .= 'b.service_type = ' . $val;
            }
            //tomrepair需求，添加多个订单编号查询
            //sqingwen 20170210
            elseif ($key == 'order_num') {
                $arr_num = explode(',' , $val);
                if (count($arr_num) == 1)//单个查询
                {
                    $where .= 'a.order_num = \'' . $val . '\'';
                }
                elseif (count($arr_num) > 1)//多个查询
                {
                    foreach ($arr_num as $k => $v) {
                        $arr_num[$k]="'".$v."'";
                    }
                    $where .= 'b.order_num in (' . implode(',',$arr_num) . ')';
                }

             }                          
			elseif($key == 'customer_name')
			{
				   $where .= 'b.consumer_name =\''.$val.'\'';
			}

            elseif (in_array($key, $fieldsOrder)) {
                $where .= in_array($key, $fieldsLike) ? "b.{$key} like '%{$val}%'" : "b.{$key}='{$val}'";
            } else {
                $where .= in_array($key, $fieldsLike) ? "a.{$key} like '%{$val}%'" : "a.{$key}='{$val}'";
            }

            $where .= ' and ';
        }
        $where = $where?' where '.rtrim($where,' and '):'';
        //#分页
        $page = (int)$gpData['page'];
        $pagesize = (int)$gpData['pagesize'];
        $page = max($page, 1);
        $pagesize = empty($pagesize) ? $pagesize = 20 : $pagesize;
        $offset = ($page - 1) * $pagesize; //显示偏移
        $fields = 'a.id as pid,a.oid,a.order_num,a.status_id,a.productSku,
            b.id,b.source_oid,b.shipinTrack,b.shipoutTrack,b.add_time order_update_time,b.currency_code,
            b.service_center,b.service_type,b.merchant_num,b.add_user,b.create_time,a.add_time,
            b.orderSubtotalBrand,b.grandTotalBrand,b.status_id as oStatus_id,b.point,b.arrivalRate,
            b.consumer_num,b.consumer_name,b.id,b.available as oAvilable,a.available';
        $sql = "
        select 
            __fields__
        from 
            mt_product a 
            left join mt_order b on a.oid = b.id 
        {$where}
        group by a.oid 
        ORDER BY a.add_time desc";

        //查询返回的数组
        //判断是否导出为excel
        if($gpData['output'] == 'excel'){
            //获取sql
            $sql = str_replace('__fields__', $fields, $sql);
            $sql = urlencode(base64_encode($sql));
            $url = site_url("sc/common/Download/export_excel_index?render=Orders&sql={$sql}");
            if ($this->input->is_ajax_request()) {
                json_output(array('url'=>$url), 'redirect', 1);
            }else{
                header("Location: {$url}");
            }
            exit;
        }
        else{
            $sql .= ' limit ' . $offset . ',' . $pagesize . ' ';
        }
        $sql = str_replace('__fields__', $fields, $sql);
		file_put_contents("./xxx.txt",   $sql.PHP_EOL,FILE_APPEND);
        $dataList = $this->common_model->getQuery($sql, 'result_array');
        //重构数据
        foreach ($dataList as $key => &$rs) {
            $serviceCenter = $this->common_model->selectFirst('mt_service_center', array('id' => $rs['service_center']));
            $serviceType = $this->common_model->selectFirst('mt_service_type', array('id' => $rs['service_type']));
            $statusFirst = $this->common_model->selectFirst('mt_order_status', array('id' => $rs['oStatus_id']));
            $consumer_num = $rs['merchant_num'] ? $rs['merchant_num'] : $rs['consumer_num'];
            $consumerFirst = $this->common_model->selectFirst('mt_customers', array('id' => $consumer_num));
            $rs['consumerName'] = $consumerFirst['name'] ? $consumerFirst['name'] : $rs['consumer_name'];
            $rs['serviceCenterName'] = $serviceCenter['name_en'];
            $rs['serviceCenterName_ch'] = $serviceCenter['name_ch'];
            $rs['serviceTypeName'] = $serviceType['name_en'];
            $rs['serviceTypeName_ch'] = $serviceType['name_ch'];
            $rs['statusName'] = $statusFirst['name_en'];
            $rs['statusName_ch'] = $statusFirst['name_ch'];
            $rs['add_time'] = date('Y-m-d H:i:s', $rs['add_time']);
            if($formData['status_id']==-1 || $rs['available'] == 2 || $rs['oAvilable']==2){
                $rs['hold_status'] = 1;
            }else{
                $rs['hold_status'] = 0;
            }
        }
        unset($rs);

        // 总记录数及页数
        $sql = preg_replace('/(select).*?(from.*?)order by.*$/is', '$1 count(1) `rows` $2', $sql);
        $sql = "select count(*) `rows` from ({$sql}) tb";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $total_rows = (int)$row['rows'];
        $pagecount = ceil($total_rows / $pagesize); //总页数

        //构造data数组
        $data = array(
            'page' => $page,
            'pagesize' => $pagesize,
            'pagecount' => $pagecount,
            'totalrows' => $total_rows,
            'dataList' => $dataList
        );
        //json判断处理
        if (empty($dataList)) {
            $message = 'No more data!';
        } else {
            $message = 'succeed!';
            $status = 1;
        }

        json_output($data, $message, $status);
    }
 /**
     * 产品列表
     */
    function products()
    {
        //输出数据结构
        $status = 0;
        $gpData = $formData = gp();  // get post data
        //查询条件
        //添加了一个order_type字段筛选20170210 sqingwen
        //应tr要求，增加, 'startDate' , 'endDate' 用于时间筛选
        $fieldsList = array('pid' , 'order_num' , 'merchant_num' , 'point' , 'status_id' , 'startTime' , 'endTime' , 'order_type' , 'startDate' , 'endDate');
        //接受参数
        $where = ' b.available !=0 and ';
        //拼接查询字符串
        foreach ($formData as $key => $val) {
            $val = trim($val);
            if (!$val || !in_array($key , $fieldsList))
                continue;
            if ($key == 'startTime' || $key == 'endTime' || $key == 'startDate' || $key == 'endDate') {
                if ($key == 'startTime' || $key == 'startDate') {
                    $where .= 'b.create_time >=\'' . $val . ' 00:00:00\'';
                }
                if ($key == 'endTime' || $key == 'endDate') {
                    $where .= 'b.create_time <=\'' . $val . ' 23:59:59\'';
                }
            }
            elseif ($key == 'merchant_num') {
                if (is_numeric($val)) {
                    $where .= 'b.merchant_num = ' . $val;
                }
                else {
                    $merchantIds = json_decode($val , true);
                    $where .= 'b.merchant_num in(' . implode(',' , $merchantIds) . ')';
                }
            }
            elseif ($key == 'status_id') {
                if ($val == '-1') {
                    $where .= '(a.available = 2 or b.available = 2)';
                }
                else {
                    $where .= 'a.status_id = ' . $val;
                }
            }
            elseif ($key == 'pid') {
                $where .= 'a.id = \'' . $val . '\'';
            }
            //tomrepair需求，添加订单类型参数筛选订单
            //sqingwen 20170210
            elseif ($key == 'order_type') {
                $where .= 'b.service_type = ' . $val;
            }
            //tomrepair需求，添加多个订单编号查询
            //sqingwen 20170210
            elseif ($key == 'order_num') {
                $arr_num = explode(',' , $val);
                if (count($arr_num) == 1)//单个查询
                {
                    $where .= 'a.order_num = \'' . $val . '\'';
                }
                elseif (count($arr_num) > 1)//多个查询
                {
                    foreach ($arr_num as $k => $v) {
                        $arr_num[$k] = "'" . $v . "'";
                    }
                    $where .= 'b.order_num in (' . implode(',' , $arr_num) . ')';
                }

            }
            else {
                $where .= "b.{$key} = '{$val}'";
            }
            $where .= ' and ';
        }
        //die($where);
        $where = $where ? ' where ' . rtrim($where , ' and ') : '';
        //#分页
        $page = (int) $gpData['page'];
        $pagesize = (int) $gpData['pagesize'];
        $page = max($page , 1);
        $pagesize = empty($pagesize) ? $pagesize = 20 : $pagesize;
        $offset = ($page - 1) * $pagesize; //显示偏移
        $sql = 'select a.id as pid,a.oid,a.order_num,a.status_id,a.productSku,
b.source_oid,b.service_center,b.service_type,b.merchant_num,b.add_user,b.create_time,a.add_time,
b.orderSubtotalBrand,b.grandTotalBrand,b.status_id as oStatus_id,b.point,b.arrivalRate,
b.consumer_num,b.consumer_name,b.id,b.available as oAvilable,a.available
from mt_product a left join mt_order b on a.oid = b.id ' . $where;
        $sql .= '  ORDER BY a.add_time desc';

        $total_rows = $this->common_model->getQuery($sql , 'num_rows');
        $pagecount = ceil($total_rows / $pagesize); //总页数
        //查询返回的数组
        $sql .= ' limit ' . $offset . ',' . $pagesize . ' ';

        $dataList = $this->common_model->getQuery($sql , 'result_array');
        //重构数据
        foreach ($dataList as $key => &$rs) {
            $serviceCenter = $this->common_model->selectFirst('mt_service_center' , array('id' => $rs['service_center']));
            $serviceType = $this->common_model->selectFirst('mt_service_type' , array('id' => $rs['service_type']));
            $statusFirst = $this->common_model->selectFirst('mt_order_status' , array('id' => $rs['oStatus_id']));

            $statusProductFirst = $this->common_model->selectFirst('mt_product_status' , array('id' => $rs['status_id']));

            $consumer_num = $rs['merchant_num'] ? $rs['merchant_num'] : $rs['consumer_num'];
            $consumerFirst = $this->common_model->selectFirst('mt_customers' , array('id' => $consumer_num));
            $rs['consumerName'] = $consumerFirst['name'] ? $consumerFirst['name'] : $rs['consumer_name'];
            $rs['serviceCenterName'] = $serviceCenter['name_en'];
            $rs['serviceCenterName_ch'] = $serviceCenter['name_ch'];
            $rs['serviceTypeName'] = $serviceType['name_en'];
            $rs['serviceTypeName_ch'] = $serviceType['name_ch'];
            $rs['statusName'] = $statusFirst['name_en'];//订单状态名
            $rs['statusName_ch'] = $statusFirst['name_ch'];//订单状态名

            $rs['status_name'] = $statusProductFirst['name_en'];//产品状态名
            $rs['add_time'] = date('Y-m-d H:i:s' , $rs['add_time']);
            if ($formData['status_id'] == -1 || $rs['available'] == 2 || $rs['oAvilable'] == 2) {
                $rs['hold_status'] = 1;
            }
            else {
                $rs['hold_status'] = 0;
            }
        }
        unset($rs);
        //构造data数组
        $data = array('page' => $page , 'pagesize' => $pagesize , 'pagecount' => $pagecount , 'totalrows' => $total_rows , 'dataList' => $dataList);
        //json判断处理2
        if (empty($dataList)) {
            $message = 'No more data!';
        }
        else {
            $message = 'succeed!';
            $status = 1;
        }
        json_output($data , $message , $status);
    }

    /**
     * 订单列表
     */
    function index2()
    {
        //输出数据结构
        $status = 0;
        $gpData = gp();  //get post data
        //接受参数
        $where = $wherein = $whereLike = array();
        $id = $gpData['id'];
        $order_num = $gpData['order_num'];
        $merchant_num = $gpData['merchant_num'];
        $point = $gpData['point'];
        $status_id = $gpData['status_id'];
        $startDate = $gpData['startDate'];
        $endDate = $gpData['endDate'];
        if ($id)
            $where['id'] = $id;
        if ($order_num)
            $whereLike['order_num'] = $order_num;
        if ($merchant_num){
            if (is_numeric($merchant_num)) {
                $where['merchant_num'] = $merchant_num;
            } else {
                $wherein['merchant_num'] = json_decode($merchant_num,true);
                if(in_array(35,$wherein['merchant_num'])){
                    $wherein['merchant_num'][] = '0';
                }
            }
        }
        if($point)
            $where['point'] = $point;
        if ($status_id)
            if($status_id=='-1'){
                $where['available'] = 2;
            }elseif($status_id == '-2'){
                $where['arrivalRate >='] = 1;
            } else{
                $where['status_id'] = $status_id;
            }
        if ($startDate)
            $where['create_time >='] = $startDate.' 00:00:00';
        if ($endDate)
            $where['create_time <='] = $endDate.' 23:59:59';
        //#分页

        //这里是设置available不等于0的订单，0为delete，1为正常，2为hold
        //$where['available !='] = '0';
        $page = (int)$gpData['page'];
        $pagesize = (int)$gpData['pagesize'];
        $page = max($page, 1);
        $pagesize = empty($pagesize) ? $pagesize = 20 : $pagesize;
        $start_limit = ($page - 1) * $pagesize; //显示偏移
        $total_rows = $this->common_model->countRows($this->t_order, $where, $wherein, $whereLike);//总数量
        $pagecount = ceil($total_rows / $pagesize); //总页数
        //查询返回的数组
        $dataList = $this->common_model->select($this->t_order, $start_limit, $pagesize, 'add_time desc', $where, $wherein, $whereLike);
        //重构数据
        foreach ($dataList as $key => &$rs) {
            $serviceCenter = $this->common_model->selectFirst('mt_service_center', array('id' => $rs['service_center']));
            $serviceType = $this->common_model->selectFirst('mt_service_type', array('id' => $rs['service_type']));
            $statusFirst = $this->common_model->selectFirst('mt_order_status', array('id' => $rs['status_id']));
            $consumer_num = $rs['merchant_num'] ? $rs['merchant_num'] : $rs['consumer_num'];
            $consumerFirst = $this->common_model->selectFirst('mt_customers', array('id' => $consumer_num));
            //查询产品 available
            $available=$this->trOrderModel->GetProductAvailable($rs['id']);
            //设置订单hold状态（此hold状态仅仅用来做显示用和订单本身hold状态不一样）
            $rs['hold_status'] = 0;
            //判断产品是否存在hold
            foreach($available as $ab){
                if($ab['available']==2){
                    $rs['hold_status'] = 1;
                }
            }
            $rs['consumerName'] = $consumerFirst['name'];
            $rs['serviceCenterName'] = $serviceCenter['name_en'];
            $rs['serviceTypeName'] = $serviceType['name_en'];
            $rs['statusName'] = $statusFirst['name_en'];
            $rs['add_time'] = date('Y-m-d H:i:s', $rs['add_time']);
        }
        unset($rs);
        //构造data数组
        $data = array(
            'page' => $page,
            'pagesize' => $pagesize,
            'pagecount' => $pagecount,
            'totalrows' => $total_rows,
            'dataList' => $dataList
        );
        //json判断处理
        if (empty($dataList)) {
            $message = 'No more data!';
        } else {
            $message = 'return succeed!';
            $status = 1;
        }
        json_output($data, $message, $status);
    }



    /**
     * 根据轨迹获取订单
     */
    function getHistoryStatus()
    {
        //输出数据结构
        $status = 0;
        $gpData = $formData = gp();  // get post data
        //获取表字段(即查询条件,时间查询额外处理)
        $oFields = array('startTime','endTime','service_center','service_type');
        $pFields = array('status_id','category_id');
        $tFields = array('end_sid','tStarTime','tEndTime');
        $fieldsList = array_merge($oFields,$pFields,$tFields);
        //接受参数
        $where = '';
        //拼接查询字符串
        foreach ($formData as $key => $val) {
            $val = trim($val);
            if (!$val || !in_array($key, $fieldsList)) continue;
            if ($key == 'startTime' || $key == 'endTime') {
                if ($key == 'startTime') {
                    $where .= 'c.create_time >=\'' . $val . ' 00:00:00\'';
                }
                if ($key == 'endTime') {
                    $where .= 'c.create_time <=\'' . $val . ' 23:59:59\'';
                }
            }elseif($key == 'tStarTime' || $key == 'tEndTime'){
                $val = strtotime($val);
                if ($key == 'tStarTime') {
                    $where .= 'a.add_time >=\'' . $val . '\'';
                }
                if ($key == 'tEndTime') {
                    $where .= 'a.add_time <=\'' . $val . '\'';
                }
            }elseif(in_array($key,$oFields)){
                $where .= 'c.' . $key . ' =\'' . $val . '\'';
            }elseif(in_array($key,$pFields)){
                $where .= 'b.' . $key . ' =\'' . $val . '\'';
            }else{
                $where .= 'a.' . $key . ' =\'' . $val . '\'';
            }
            $where .= ' and ';
        }
        $where = $where?' where '.rtrim($where,' and '):'';
        //#分页
        $page = (int)$gpData['page'];
        $pagesize = (int)$gpData['pagesize'];
        $page = max($page, 1);
        $pagesize = empty($pagesize) ? $pagesize = 20 : $pagesize;
        $offset = ($page - 1) * $pagesize; //显示偏移
        $sql = 'select a.pid,a.oid,a.order_num,a.productSku,a.end_sid,a.add_time,a.add_user,
                b.category_id,b.product_model,b.brandCustomerNum,b.defectDes,b.customerRemark,b.status_id,
                c.source_oid,c.service_center,c.service_type,c.create_time
                from mt_product_track as a
                left join mt_product as b on a.pid = b.id
                left join mt_order as c on a.oid = c.id '.$where;
        $total_rows = $this->common_model->getQuery($sql, 'num_rows');
        $pagecount = ceil($total_rows / $pagesize); //总页数
        //查询返回的数组
        $sql .= ' order by c.create_time desc limit ' . $offset . ',' . $pagesize . ' ';
        $dataList = $this->common_model->getQuery($sql, 'result_array');
        //重构数据
        foreach ($dataList as $key => &$rs) {
            $serviceCenter = $this->common_model->selectFirst('mt_service_center', array('id' => $rs['service_center']));
            $rs['siteName'] = $serviceCenter['name_en'];
            $rs['siteName_ch'] = $serviceCenter['name_ch'];
            $rs['addTime'] = date('Y-m-d H:i:s',$rs['add_time']);
        }
        unset($rs);
        //构造data数组
        $data = array(
            'page' => $page,
            'pagesize' => $pagesize,
            'pagecount' => $pagecount,
            'totalrows' => $total_rows,
            'dataList' => $dataList
        );
        gsh_output($data);
        /*
        //json判断处理
        if (empty($dataList)) {
            $message = 'No more data!';
        } else {
            $message = 'return succeed!';
            $status = 1;
        }
        json_output($data, $message, $status);
        */
    }




    /**
     * 获取单个订单信息
     */
    function get_order_one()
    {
        //判断处理输出
        $data = array();
        $status = 0;
        //order id  or order number
        $id = $this->input->get_post('id');
        if(is_numeric($id)){
            $where = array('id' => $id);
        }else{
            $where = array('order_num' => $id);
        }
        //#订单
        $orderFirst = $this->common_model->selectFirst('mt_order', $where);
        $id = $orderFirst['id'];
        if (!$orderFirst) {
            json_output($id, 'Order not exist', $status);
        }
        $serviceCenter = $this->common_model->selectFirst('mt_service_center', array('id' => $orderFirst['service_center']));
        $serviceType = $this->common_model->selectFirst('mt_service_type', array('id' => $orderFirst['service_type']));
        $statusFirst = $this->common_model->selectFirst('mt_order_status', array('id' => $orderFirst['status_id']));
        $consumer_num = $orderFirst['merchant_num'] ? $orderFirst['merchant_num'] : $orderFirst['consumer_num'];
        $consumerFirst = $this->common_model->selectFirst('mt_customers', array('id' => $consumer_num));
        $orderFirst['statusName'] = $statusFirst['name_en'];
        $orderFirst['statusName_ch'] = $statusFirst['name_ch'];
        $orderFirst['serviceCenterName'] = $serviceCenter['name_en'];
        $orderFirst['serviceCenterName_ch'] = $serviceCenter['name_ch'];
        $orderFirst['serviceTypeName'] = $serviceType['name_en'];
        $orderFirst['serviceTypeName_ch'] = $serviceType['name_ch'];
	 if($consumer_num =='1028')
	    {
	   	 $currency = $this->common_model->selectFirst('mt_product_rate', array('order_num' => $orderFirst['order_num']));
			$orderFirst['shippingFee']=number_format($orderFirst['shippingFee']*$currency['rate'], 2, '.', ''); 
	$orderFirst['shippingFeeBrand']=number_format($orderFirst['shippingFeeBrand']*$currency['rate'], 2, '.', ''); 
	$orderFirst['shippingFeeIndividualUser']=number_format($orderFirst['shippingFeeIndividualUser']*$currency['rate'], 2, '.', ''); 
	$orderFirst['shippingFeeMerchant']=number_format($orderFirst['shippingFeeMerchant']*$currency['rate'], 2, '.', ''); 
	$orderFirst['orderSubtotal']=number_format($orderFirst['orderSubtotal']*$currency['rate'], 2, '.', ''); 
	$orderFirst['orderSubtotalBrand']=number_format($orderFirst['orderSubtotalBrand']*$currency['rate'], 2, '.', ''); 
	$orderFirst['orderSubtotalIndividualUser']=number_format($orderFirst['orderSubtotalIndividualUser']*$currency['rate'], 2, '.', ''); 
	$orderFirst['orderSubtotalMerchant']=number_format($orderFirst['orderSubtotalMerchant']*$currency['rate'], 2, '.', ''); 
	$orderFirst['discountAmount']=number_format($orderFirst['discountAmount']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['discountAmountBrand']=number_format($orderFirst['discountAmountBrand']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['discountAmountIndividualUser']=number_format($orderFirst['discountAmountIndividualUser']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['discountAmountMerchant']=number_format($orderFirst['discountAmountMerchant']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['grandTotal']=number_format($orderFirst['grandTotal']*$currency['rate'], 2, '.', ''); 
		$orderFirst['grandTotalBrand']=number_format($orderFirst['grandTotalBrand']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['grandTotalIndividualUser']=number_format($orderFirst['grandTotalIndividualUser']*$currency['rate'], 2, '.', ''); 
		$orderFirst['grandTotalMerchant']=number_format($orderFirst['grandTotalMerchant']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['supplementAmount']=number_format($orderFirst['supplementAmount']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['supplementAmountBrand']=number_format($orderFirst['supplementAmountBrand']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['supplementAmountIndividualUser']=number_format($orderFirst['supplementAmountIndividualUser']*$currency['rate'], 2, '.', '');	
	$orderFirst['supplementAmountMerchant']=number_format($orderFirst['supplementAmountMerchant']*$currency['rate'], 2, '.', ''); 
		$orderFirst['amount_paid']=number_format($orderFirst['amount_paid']*$currency['rate'], 2, '.', ''); 
		$orderFirst['discountShippingFee']=number_format($orderFirst['discountShippingFee']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['taxSubtotal']=number_format($orderFirst['taxSubtotal']*$currency['rate'], 2, '.', ''); 	
	$orderFirst['shippingFeeText']=number_format($orderFirst['shippingFeeText']*$currency['rate'], 2, '.', ''); 	
	        $orderFirst['currency_code'] = 'CNY';
	}
        
        $orderFirst['customerData'] = $consumerFirst;
        $data['orderData'] = $orderFirst;
        //#产品列表
        $productList = $this->common_model->selectCustom('mt_product', array('oid' => $id));
        foreach ($productList as &$rs) {
            $categoryFirst = $this->common_model->selectFirst('mt_product_category', array('id' => $rs['category_id']));
            $statusFirst = $this->common_model->selectFirst('mt_product_status', array('id' => $rs['status_id']));
            $consumerFirst = $this->common_model->selectFirst('mt_customers', array('id' => $rs['brandCustomerNum']));
            $rs['brandCustomerData'] = $consumerFirst;
            $rs['brandCustomerName'] = $consumerFirst['name'];
            $rs['category_name'] = $categoryFirst['name_en'];
            $rs['category_name_ch'] = $categoryFirst['name_ch'];
            $rs['status_name'] = $statusFirst['name_en'];
            $rs['status_name_ch'] = $statusFirst['name_ch'];
	    $rs['barcode']='';
	      if($consumer_num =='1028'){
	      
	            
		    $rs['merchantSubTotal'] = number_format($rs['merchantSubTotal']*$currency['rate'], 2, '.', '');  
		    $rs['NAQAmount'] = number_format($rs['NAQAmount']*$currency['rate'], 2, '.', '');  
	      }
	    }
        unset($rs);
        $data['productList'] = $productList;
        //#维修轨迹
        $trackList = $this->common_model->selectCustom('mt_order_track', array('oid' => $id),'id desc');
        foreach ($trackList as &$rs) {
            $startStatus = $this->common_model->selectFirst('mt_order_status', array('id' => $rs['start_sid']));
            $rs['startName_en'] = $startStatus['name_en'];
            $rs['startName_es'] = $startStatus['name_es'];
            $rs['startName_ch'] = $startStatus['name_ch'];
            $endStatus = $this->common_model->selectFirst('mt_order_status', array('id' => $rs['end_sid']));
            $rs['endName_en'] = $endStatus['name_en'];
            $rs['endName_es'] = $endStatus['name_es'];
            $rs['endName_ch'] = $endStatus['name_ch'];
            $rs['is_sync'] = $rs['is_sync'] ? 'Yes' : 'No';
            $rs['add_time'] = date('Y-m-d H:i:s', $rs['add_time']);
        }
        unset($rs);
        $data['trackList'] = $trackList;
        //#追踪号
        $packageList = $this->common_model->selectCustom('mt_package',array('order_id'=>$orderFirst['order_num']));
        $data['packageList'] = $packageList;
        $message = 'successful';
        $status = 1;
        json_output($data, $message, $status);
    }

    /**
     * 批量单订单列表
     */
    function get_multi_page() {
        //张伟 20170613 用查询构造器方法查询订单和订单产品
        $post = gp();//$this->input->post();
        $page = $post['page'] ? (int)$post['page'] : 1;
        $pagesize = empty($post['pagesize']) ? 20 : (int) $post['pagesize'];
        $start_limit = ($page - 1) * $pagesize; //显示偏移

        $fields = 'o.*,p.imei,p.waybill_num,p.shipping_num';
        $fieldsLike = array(
            'order_num' => 'o',
            'source_oid' => 'o',
            'waybill_num' => 'p',
            'imei' => 'p',
            'shipping_num' => 'p'
        );
        $this->db->from('mt_multi_orders o');
        $this->db->join('mt_multi_products p', 'p.oid = o.id', 'left');
        $this->db->select($fields);
        //订单id
        if (is_numeric($post['id'])) {
            $this->db->where('o.id', $post['id']);
        }
        //站点标识
        if ($post['point']) {
            $this->db->where('o.point', $post['point']);
        }
        //订单时间
        if ($post['startDate']){
            $startDate = strtotime("{$post['startDate']} 00:00:00");
            $this->db->where("o.add_time >= '{$startDate}'");
        }
        if ($post['endDate']){
            $endDate = strtotime("{$post['endDate']} 23:59:59");
            $this->db->where("o.add_time <= '{$endDate}'");
        }
        //模糊搜索
        foreach ($fieldsLike as $f => $tb) {
            if(trim($post[$f]))
                $this->db->where("{$tb}.{$f} like '%{$post[$f]}%'");
        }
        //商家编号
        if ($post['merchant_num']) {
            if (is_numeric($post['merchant_num'])) {
                $this->db->where('o.merchant_num', $post['merchant_num']);
            } else {
                $post['merchant_num'] = json_decode($post['merchant_num'], true);
                if (in_array(35, $post['merchant_num'])) {
                    $post['merchant_num'][] = '0';
                }
                $this->db->where_in('o.merchant_num', $post['merchant_num']);
            }
        }
        //分组
        $this->db->group_by('o.id');
        //排序
        $this->db->order_by('o.add_time desc');
        //判断是否导出为excel
        if($post['output'] == 'excel'){
            //获取sql
            $this->db->get();
            $sql = $this->db->last_query();
            $sql = urlencode(base64_encode($sql));
            $url = site_url("sc/common/Download/export_excel_index?render=MultiOrders&sql={$sql}");
            if ($this->input->is_ajax_request()) {
                json_output(array('url'=>$url), 'redirect', 1);
            }else{
                header("Location: {$url}");
            }
            exit;
        }
        //区间
        $this->db->limit($pagesize, $start_limit);
        //结果集
        $query = $this->db->get()->result_array();
        $dataList = array();
        foreach ($query as $row) {
            array_push($dataList, $row);
        }
        //统计数量
        $sql = $this->db->last_query();//echo $sql;
        $sql = substr($sql, 0, stripos($sql, 'ORDER BY'));
        $sql = preg_replace('/(SELECT).*?(FROM.*)/is', '$1 count(*) `rows` $2', $sql);
        $sql = "select count(*) `rows` from ({$sql}) tb";
        $query = $this->db->query($sql);
        $row = $query->row_array();
        $total_rows = (int)$row['rows']; //总数量
        $pagecount = ceil($total_rows / $pagesize); //总页数

/*--------------------------以前的逻辑
        //输出数据结构
        $status = 0;
        $gpData = gp();  //get post data
        //接受参数
        $where = $wherein = $whereLike = array();
        $id = $gpData['id'];
        $order_num = $gpData['order_num'];
        $merchant_num = $gpData['merchant_num'];
        $point = $gpData['point'];
        $status_id = $gpData['status_id'];
        $startDate = $gpData['startDate'];
        $endDate = $gpData['endDate'];
        if ($id)
            $where['id'] = $id;
        if ($order_num)
            $whereLike['order_num'] = $order_num;
        if ($merchant_num) {
            if (is_numeric($merchant_num)) {
                $where['merchant_num'] = $merchant_num;
            } else {
                $wherein['merchant_num'] = json_decode($merchant_num, true);
                if (in_array(35, $wherein['merchant_num'])) {
                    $wherein['merchant_num'][] = '0';
                }
            }
        }
        if ($point)
            $where['point'] = $point;

        if ($startDate)
            $where['add_time >='] = $startDate . ' 00:00:00';
        if ($endDate)
            $where['add_time <='] = $endDate . ' 23:59:59';
        //#分页
        //这里是设置available不等于0的订单，0为delete，1为正常，2为hold

        $page = (int) $gpData['page'];
        $pagesize = (int) $gpData['pagesize'];
        $page = max($page, 1);
        $pagesize = empty($pagesize) ? $pagesize = 20 : $pagesize;
        $start_limit = ($page - 1) * $pagesize; //显示偏移
        $total_rows = $this->common_model->countRows('mt_multi_orders', $where, $wherein, $whereLike); //总数量
        $pagecount = ceil($total_rows / $pagesize); //总页数
        //查询返回的数组
        $dataList = $this->common_model->select('mt_multi_orders', $start_limit, $pagesize, 'add_time desc', $where, $wherein, $whereLike);
        */
        //重构数据
        foreach ($dataList as $key => &$rs) {
            $serviceCenter = $this->common_model->selectFirst('mt_service_center', array('id' => $rs['service_center']));
            $serviceType = $this->common_model->selectFirst('mt_service_type', array('id' => $rs['service_type']));
            $statusFirst = $this->common_model->selectFirst('mt_order_status', array('id' => $rs['status_id']));
            $consumer_num = $rs['merchant_num'] ? $rs['merchant_num'] : $rs['consumer_num'];
            $consumerFirst = $this->common_model->selectFirst('mt_customers', array('id' => $consumer_num));
            //查询产品 available
            $available = $this->trOrderModel->GetProductAvailable($rs['id']);
            //设置订单hold状态（此hold状态仅仅用来做显示用和订单本身hold状态不一样）
            $rs['hold_status'] = 0;
            //判断产品是否存在hold
            foreach ($available as $ab) {
                if ($ab['available'] == 2) {
                    $rs['hold_status'] = 1;
                }
            }
            $rs['consumerName'] = $consumerFirst['name'];
            $rs['serviceCenterName'] = $serviceCenter['name_en'];
            $rs['serviceTypeName'] = $serviceType['name_en'];
            $rs['statusName'] = $statusFirst['name_en'];
            $rs['percent_complete'] = 0.0;
            $rs['add_time'] = date('Y-m-d H:i:s' , $rs['add_time']);
            //计算修好的产品数量
            $comp = $this->common_model->countRows('mt_multi_products' , array('order_num' => $rs['order_num'] , 'is_finnish' => 1));
            if ($comp == 0 || $rs['quantity'] == 0 || $rs['actual_quantity'] == 0) {//如果有任意一个为0，都不需要计算了
                $rs['percent_complete'] = 0.0;
            }
            else {
                if ($rs['actual_quantity'] > $rs['quantity']) {//如果 实际来货数量>预计数量，则百分比为 ： 修好的数量/ 实际来货数量
                    $rs['percent_complete'] = sprintf("%.2f" , ($comp / intval($rs['actual_quantity'])) * 100);
                }
                else {//实际数量小于预计数量，则按照正常计算
                    $rs['percent_complete'] = sprintf("%.2f" , ($comp / intval($rs['quantity'])) * 100);
                }
            }
        }
        unset($rs);
        //构造data数组
        $data = array('page' => $page, 'pagesize' => $pagesize, 'pagecount' => $pagecount, 'totalrows' => $total_rows, 'dataList' => $dataList);
        //json判断处理
        if (empty($dataList)) {
            $message = 'No more data!';
        } else {
            $message = 'return succeed!';
            $status = 1;
        }

        json_output($data, $message, $status);
    }

    /**
     * 
     */
    function get_multi_orders_by_num() {
        $gpData = gp();  //get post data

        $message = 'successful';
        $status = 1;
        $id = $gpData['id'];
        if (is_numeric($id)) {
            $where = array('id' => $id);
        } else {
            $where = array('order_num' => $id);
        }
        //#订单
        $orderFirst = $this->common_model->selectFirst('mt_multi_orders', $where);

        $wy = $this->common_model->getQuery(sprintf("select `add_time`,`waybill_num`,`quantity` from mt_multi_waybill where order_num = '%s'", $orderFirst['order_num']), 'result_array');
        $orderFirst['waybill'] = $wy;
        $id = $orderFirst['id'];
        if (!$orderFirst) {
            json_output($id, 'Order not exist', $status);
        }
        json_output($orderFirst, $message, $status);
    }

    function get_multi_orders_by_num_2()
    {
        $this->load->model('multi_model');
        $gpData = gp();  //get post data
        $message = 'successful';
        $status = 1;
        $id = $gpData['id'];
        if (is_numeric($id)) {
           return;
        }
        else {
            $where = array('order_num' => $id);
        }
        //-----------------------------------------------------------------------
        $order_info = $this->common_model->selectFirst('mt_multi_orders' , $where);
        $waybill_info = $this->common_model->selectCustom('mt_multi_waybill' , $where);
        foreach ($waybill_info as $k => $v) {
            $product_info = $this->multi_model->GetProductsByWaybillNum($v['waybill_num']);
            $waybill_info[$k]['product_info'] = $product_info;
        }
        $order_info['waybill'] = $waybill_info;
        //-----------------------------------------------------------------------


        json_output($order_info , $message , $status);
    }
    function get_multi_orders_by_num_3()
    {
        $this->load->model('multi_model');
        $gpData = gp();  //get post data
	$message = 'successful';
        $status = 1;
        $id = $gpData['id'];      
         $where = array('waybill_num' => $id);      
        $waybill_info = $this->common_model->selectCustom('mt_multi_waybill' , $where);
        foreach ($waybill_info as $k => $v) {
            $product_info = $this->multi_model->GetProductsByWaybillNum($v['waybill_num']);
            $waybill_info[$k]['product_info'] = $product_info;
        }
        $order_info['waybill'] = $waybill_info;
        json_output($waybill_info , $message , $status);
    }
    
    
     function get_multi_orders_by_num_2_en()
    {
        $this->load->model('multi_model');
        $gpData = gp();  //get post data
        $message = 'successful';
        $status = 1;
        $id = $gpData['id'];
        if (is_numeric($id)) {
           return;
        }
        else {
            $where = array('order_num' => $id);
        }
        //-----------------------------------------------------------------------
        $order_info = $this->common_model->selectFirst('mt_multi_orders' , $where);
        $waybill_info = $this->common_model->selectCustom('mt_multi_waybill' , $where);
        foreach ($waybill_info as $k => $v) {
            $product_info = $this->multi_model->GetProductsByWaybillNumEn($v['waybill_num']);
            $waybill_info[$k]['product_info'] = $product_info;
        }
        $order_info['waybill'] = $waybill_info;
        //-----------------------------------------------------------------------

        json_output($order_info , $message , $status);
    }
    function get_multi_orders_by_num_3_en()
    {
        $this->load->model('multi_model');
        $gpData = gp();  //get post data	
	$message = 'successful';
        $status = 1;
        $id = $gpData['id'];      
         $where = array('waybill_num' => $id);      
        $waybill_info = $this->common_model->selectCustom('mt_multi_waybill' , $where);
        foreach ($waybill_info as $k => $v) {
            $product_info = $this->multi_model->GetProductsByWaybillNumEn($v['waybill_num']);
            $waybill_info[$k]['product_info'] = $product_info;
        }
        $order_info['waybill'] = $waybill_info;
        json_output($waybill_info , $message , $status);
    }
}
